package net.sql;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import net.sql.bean.SqlParam;
import net.sql.config.SQLBean;
import net.sql.config.SQLConfig;
import net.sql.i.IDataRow;
import net.sql.i.IDbRow;
import net.sql.i.IRow;
import net.sql.i.ISqlListener;

/**
 * @author 李岩飞
 * @email eliyanfei@126.com
 * @date 2018年7月20日上午9:22:18
 */
public class SqlProxy implements InvocationHandler {

	public Object getInstance(Class<?> cls) {
		Object newProxyInstance = Proxy.newProxyInstance(cls.getClassLoader(), new Class[] { cls }, this);
		return (Object) newProxyInstance;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		IRow row = null;
		if (args.length == 2 && args[1] instanceof IRow) {
			row = (IRow) args[1];
		}
		return run(method, (SqlParam) args[0], row);
	}

	/**
	 * 实现接口的核心方法
	 */
	public Object run(Method method, SqlParam sqlParam, IRow row) {
		long t = System.currentTimeMillis();
		SQLBean sqlBean = SQLConfig.getSqlConfig().getSQL(sqlParam.getSqlName());
		if (sqlBean == null)
			return null;
		for (ISqlListener listener : SQLConfig.getSqlConfig().getListener()) {
			listener.beforeListener(sqlBean);
		}
		Object obj = null;
		SqlConnector connector = new SqlConnector(sqlBean, sqlParam);
		String name = method.getName();
		if ("query".equals(name) && row != null && row instanceof IDbRow) {// 自定义查询
			connector.query((IDbRow) row);
		} else if ("query".equals(name) && row != null && row instanceof IDataRow) {// 自定义查询
			connector.query((IDataRow) row);
		} else if ("query".equals(name)) {// 普通查询
			obj = connector.query();
		} else if ("queryOne".equals(name)) {// 普通查询
			obj = connector.queryOne();
		} else if ("queryMap".equals(name)) {// 普通查询
			obj = connector.queryMap();
		} else if ("queryKeyMap".equals(name)) {// 普通查询
			obj = connector.queryKeyMap();
		} else if ("pageQuery".equals(name) && row != null) {// 分页查询
			obj = connector.queryPage((IDataRow) row);
		} else if ("pageQuery".equals(name)) {// 分页查询
			obj = connector.queryPage();
		} else if ("execute".equals(name)) {// 增删改
			obj = connector.execute();
		} else if ("count".equals(name)) {// 数值统计
			obj = connector.count();
		} else if ("id".equals(name)) {// ID值
			obj = connector.id();
		} else if ("getSql".equals(name)) {// ID值
			obj = connector.getSql();
		}

		sqlParam.setSelectSql(connector.getSql());

		for (ISqlListener listener : SQLConfig.getSqlConfig().getListener()) {
			listener.afterListener(sqlBean, connector, System.currentTimeMillis() - t);
		}
		return obj;
	}
}
